// 全局变量
let currentUser = null;
let currentPage = 1;
let currentPostId = null;

// API 基础URL
const API_BASE = '/api/v1';

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    checkAuthStatus();
    showHome();
});

// 检查认证状态
function checkAuthStatus() {
    const token = localStorage.getItem('token');
    if (token) {
        // 验证token有效性
        fetch(`${API_BASE}/auth/profile`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error('Token无效');
            }
        })
        .then(data => {
            currentUser = data.user;
            updateNavigation(true);
        })
        .catch(error => {
            localStorage.removeItem('token');
            updateNavigation(false);
        });
    } else {
        updateNavigation(false);
    }
}

// 更新导航栏
function updateNavigation(isLoggedIn) {
    const loginLink = document.getElementById('loginLink');
    const registerLink = document.getElementById('registerLink');
    const logoutLink = document.getElementById('logoutLink');
    const myPostsLink = document.getElementById('myPostsLink');
    const createPostLink = document.getElementById('createPostLink');
    const userInfo = document.getElementById('userInfo');
    const currentUsername = document.getElementById('currentUsername');

    if (isLoggedIn) {
        loginLink.style.display = 'none';
        registerLink.style.display = 'none';
        logoutLink.style.display = 'inline';
        myPostsLink.style.display = 'inline';
        createPostLink.style.display = 'inline';
        userInfo.style.display = 'inline';
        
        // 显示当前用户名
        if (currentUser && currentUser.username) {
            currentUsername.textContent = currentUser.username;
        }
    } else {
        loginLink.style.display = 'inline';
        registerLink.style.display = 'inline';
        logoutLink.style.display = 'none';
        myPostsLink.style.display = 'none';
        createPostLink.style.display = 'none';
        userInfo.style.display = 'none';
        currentUsername.textContent = '';
    }
}

// 显示消息
function showMessage(message, type = 'info') {
    const messageEl = document.getElementById('message');
    messageEl.textContent = message;
    messageEl.className = `message ${type}`;
    messageEl.classList.add('show');
    
    setTimeout(() => {
        messageEl.classList.remove('show');
    }, 3000);
}

// 显示加载状态
function showLoading() {
    document.getElementById('loading').style.display = 'block';
}

// 隐藏加载状态
function hideLoading() {
    document.getElementById('loading').style.display = 'none';
}

// 隐藏所有内容区域
function hideAllSections() {
    const sections = ['loginForm', 'registerForm', 'createPostForm', 'editPostForm', 'postsList', 'postDetail', 'myPostsList'];
    sections.forEach(id => {
        document.getElementById(id).style.display = 'none';
    });
}

// 显示首页
function showHome() {
    hideAllSections();
    document.getElementById('postsList').style.display = 'block';
    loadPosts();
}

// 显示登录表单
function showLogin() {
    hideAllSections();
    document.getElementById('loginForm').style.display = 'block';
}

// 显示注册表单
function showRegister() {
    hideAllSections();
    document.getElementById('registerForm').style.display = 'block';
}

// 显示创建文章表单
function showCreatePost() {
    if (!currentUser) {
        showMessage('请先登录', 'error');
        return;
    }
    hideAllSections();
    document.getElementById('createPostForm').style.display = 'block';
    // 清空表单
    document.getElementById('postTitle').value = '';
    document.getElementById('postContent').value = '';
}

// 显示我的文章
function showMyPosts() {
    if (!currentUser) {
        showMessage('请先登录', 'error');
        return;
    }
    hideAllSections();
    document.getElementById('myPostsList').style.display = 'block';
    loadMyPosts();
}

// 用户注册
function register(event) {
    event.preventDefault();
    
    const username = document.getElementById('registerUsername').value;
    const email = document.getElementById('registerEmail').value;
    const password = document.getElementById('registerPassword').value;
    
    showLoading();
    
    fetch(`${API_BASE}/auth/register`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, email, password })
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.message) {
            showMessage(data.message, 'success');
            showLogin();
        } else {
            showMessage(data.error || '注册失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('注册失败: ' + error.message, 'error');
    });
}

// 用户登录
function login(event) {
    event.preventDefault();
    
    const username = document.getElementById('loginUsername').value;
    const password = document.getElementById('loginPassword').value;
    
    showLoading();
    
    fetch(`${API_BASE}/auth/login`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.token) {
            localStorage.setItem('token', data.token);
            currentUser = data.user;
            updateNavigation(true);
            showMessage(data.message, 'success');
            showHome();
        } else {
            showMessage(data.error || '登录失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('登录失败: ' + error.message, 'error');
    });
}

// 用户退出
function logout() {
    localStorage.removeItem('token');
    currentUser = null;
    updateNavigation(false);
    showMessage('已退出登录', 'info');
    showHome();
}

// 创建文章
function createPost(event) {
    event.preventDefault();
    
    const title = document.getElementById('postTitle').value;
    const content = document.getElementById('postContent').value;
    const token = localStorage.getItem('token');
    
    showLoading();
    
    fetch(`${API_BASE}/posts`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ title, content })
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.message) {
            showMessage(data.message, 'success');
            showHome();
        } else {
            showMessage(data.error || '创建文章失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('创建文章失败: ' + error.message, 'error');
    });
}

// 更新文章
function updatePost(event) {
    event.preventDefault();
    
    const id = document.getElementById('editPostId').value;
    const title = document.getElementById('editPostTitle').value;
    const content = document.getElementById('editPostContent').value;
    const token = localStorage.getItem('token');
    
    showLoading();
    
    fetch(`${API_BASE}/posts/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ title, content })
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.message) {
            showMessage(data.message, 'success');
            showHome();
        } else {
            showMessage(data.error || '更新文章失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('更新文章失败: ' + error.message, 'error');
    });
}

// 加载文章列表
function loadPosts(page = 1) {
    showLoading();
    
    fetch(`${API_BASE}/posts?page=${page}&limit=10`)
    .then(response => response.json())
    .then(data => {
        hideLoading();
        displayPosts(data.posts, 'postsContent');
        displayPagination(data.pagination, 'pagination', loadPosts);
    })
    .catch(error => {
        hideLoading();
        showMessage('加载文章失败: ' + error.message, 'error');
    });
}

// 加载我的文章
function loadMyPosts(page = 1) {
    const token = localStorage.getItem('token');
    showLoading();
    
    fetch(`${API_BASE}/my-posts?page=${page}&limit=10`, {
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        displayMyPosts(data.posts, 'myPostsContent');
        displayPagination(data.pagination, 'myPostsPagination', loadMyPosts);
    })
    .catch(error => {
        hideLoading();
        showMessage('加载文章失败: ' + error.message, 'error');
    });
}

// 显示文章列表
function displayPosts(posts, containerId, showActions = false) {
    const container = document.getElementById(containerId);
    
    if (!posts || posts.length === 0) {
        container.innerHTML = '<p style="text-align: center; color: #666;">暂无文章</p>';
        return;
    }
    
    container.innerHTML = posts.map(post => `
        <div class="post-item fade-in">
            <h3 class="post-title">${post.title}</h3>
            <div class="post-meta">
                <span><i class="fas fa-user"></i> ${post.user.username}</span>
                <span><i class="fas fa-calendar"></i> ${new Date(post.created_at).toLocaleDateString('zh-CN')}</span>
                <span id="commentCount-${post.id}"><i class="fas fa-comments"></i> <span id="commentCountText-${post.id}">0</span> 评论</span>
            </div>
            <div class="post-content">${post.content.replace(/\n/g, '<br>')}</div>
            ${showActions && currentUser && post.user_id === currentUser.id ? `
                <div class="post-actions">
                    <button class="btn btn-small btn-secondary" onclick="editPost(${post.id})">编辑</button>
                    <button class="btn btn-small btn-danger" onclick="deletePost(${post.id})">删除</button>
                </div>
            ` : ''}
            
            <!-- 评论按钮 -->
            <div class="comment-actions" style="margin-top: 15px;">
                <button class="btn btn-primary btn-small" onclick="toggleComments(${post.id})" id="commentBtn-${post.id}">
                    <i class="fas fa-comment"></i> 查看评论
                </button>
                ${currentUser ? `
                    <button class="btn btn-secondary btn-small" onclick="toggleCommentForm(${post.id})" id="writeCommentBtn-${post.id}">
                        <i class="fas fa-edit"></i> 写评论
                    </button>
                ` : ''}
            </div>
            
            <!-- 评论表单 -->
            <div id="commentForm-${post.id}" class="comment-form" style="display: none; margin-top: 15px;">
                ${currentUser ? `
                    <form onsubmit="submitComment(event, ${post.id})">
                        <div class="form-group">
                            <textarea id="commentContent-${post.id}" placeholder="写下你的评论..." rows="3" required maxlength="500" oninput="updateCharCount(${post.id})"></textarea>
                            <div style="text-align: right; margin-top: 5px; color: #666; font-size: 0.9rem;">
                                <span id="charCount-${post.id}">0</span>/500
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary btn-small">发表评论</button>
                        <button type="button" class="btn btn-secondary btn-small" onclick="toggleCommentForm(${post.id})">取消</button>
                    </form>
                ` : `
                    <div style="text-align: center; padding: 20px; background-color: #f8f9fa; border-radius: 5px;">
                        <p style="margin-bottom: 15px; color: #666;">请先登录后发表评论</p>
                        <button class="btn btn-primary btn-small" onclick="showLogin()">立即登录</button>
                        <button class="btn btn-secondary btn-small" onclick="showRegister()">注册账号</button>
                    </div>
                `}
            </div>
            
            <!-- 评论列表 -->
            <div id="commentsList-${post.id}" class="comments-list" style="display: none; margin-top: 15px;">
            </div>
        </div>
    `).join('');
    
    // 为每个文章加载评论数 - 添加延迟确保DOM元素已渲染
    setTimeout(() => {
        posts.forEach(post => {
            console.log(`Loading comment count for post ${post.id} in container ${containerId}`);
            loadCommentCountForPost(post.id);
        });
    }, 100);
}

// 显示我的文章列表 - 直接调用displayPosts函数
function displayMyPosts(posts, containerId) {
    console.log('displayMyPosts called with posts:', posts);
    console.log('displayMyPosts called with containerId:', containerId);
    
    // 直接调用首页的displayPosts函数，但显示编辑删除按钮
    displayPosts(posts, containerId, true);
}

// 截断文本
function truncateText(text, maxLength) {
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
}

// 显示分页
function displayPagination(pagination, containerId, loadFunction) {
    const container = document.getElementById(containerId);
    const { page, total, limit } = pagination;
    const totalPages = Math.ceil(total / limit);
    
    if (totalPages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    let paginationHTML = '';
    
    // 上一页
    if (page > 1) {
        paginationHTML += `<button onclick="${loadFunction.name}(${page - 1})">上一页</button>`;
    }
    
    // 页码
    for (let i = Math.max(1, page - 2); i <= Math.min(totalPages, page + 2); i++) {
        paginationHTML += `<button class="${i === page ? 'current-page' : ''}" onclick="${loadFunction.name}(${i})">${i}</button>`;
    }
    
    // 下一页
    if (page < totalPages) {
        paginationHTML += `<button onclick="${loadFunction.name}(${page + 1})">下一页</button>`;
    }
    
    container.innerHTML = paginationHTML;
}

// 显示文章详情
function showPostDetail(id) {
    showLoading();
    
    fetch(`${API_BASE}/posts/${id}`)
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.post) {
            hideAllSections();
            document.getElementById('postDetail').style.display = 'block';
            displayPostDetail(data.post);
            loadComments(id);
        } else {
            showMessage(data.error || '加载文章失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('加载文章失败: ' + error.message, 'error');
    });
}

// 显示文章详情内容
function displayPostDetail(post) {
    console.log('🔄 JavaScript已更新 - 评论功能已启用');
    const container = document.getElementById('postContent');
    currentPostId = post.id;
    
    container.innerHTML = `
        <div class="fade-in">
            <h1>${post.title}</h1>
            <div class="post-meta">
                <span><i class="fas fa-user"></i> ${post.user.username}</span>
                <span><i class="fas fa-calendar"></i> ${new Date(post.created_at).toLocaleDateString('zh-CN')}</span>
                <span><i class="fas fa-clock"></i> ${new Date(post.updated_at).toLocaleDateString('zh-CN')} 更新</span>
                <span id="commentCountDisplay"><i class="fas fa-comments"></i> 0评论</span>
            </div>
            <div class="post-content">${post.content.replace(/\n/g, '<br>')}</div>
            ${currentUser && post.user_id === currentUser.id ? `
                <div class="post-actions">
                    <button class="btn btn-secondary" onclick="editPost(${post.id})">编辑文章</button>
                    <button class="btn btn-danger" onclick="deletePost(${post.id})">删除文章</button>
                </div>
            ` : ''}
            <div class="post-actions" style="margin-top: 20px;">
                <button class="btn btn-primary" onclick="scrollToComments()">
                    <i class="fas fa-comment"></i> 查看评论
                </button>
                ${currentUser ? `
                    <button class="btn btn-secondary" onclick="scrollToCommentForm()">
                        <i class="fas fa-edit"></i> 写评论
                    </button>
                ` : ''}
            </div>
        </div>
    `;
    
    // 显示评论表单
    const commentForm = document.getElementById('commentForm');
    const commentPostId = document.getElementById('commentPostId');
    if (currentUser) {
        // 恢复原始表单结构（如果被修改过）
        commentForm.innerHTML = `
            <form onsubmit="createComment(event)">
                <input type="hidden" id="commentPostId">
                <div class="form-group">
                    <textarea id="commentContent" placeholder="写下你的评论..." rows="3" required maxlength="500" oninput="updateCharCount()"></textarea>
                    <div style="text-align: right; margin-top: 5px; color: #666; font-size: 0.9rem;">
                        <span id="charCount">0</span>/500
                    </div>
                </div>
                <button type="submit" class="btn btn-primary">发表评论</button>
            </form>
        `;
        commentForm.style.display = 'block';
        document.getElementById('commentPostId').value = post.id;
    } else {
        // 为未登录用户显示登录提示
        commentForm.innerHTML = `
            <div style="text-align: center; padding: 20px; background-color: #f8f9fa; border-radius: 5px; margin-bottom: 20px;">
                <p style="margin-bottom: 15px; color: #666;">请先登录后发表评论</p>
                <button class="btn btn-primary" onclick="showLogin()">立即登录</button>
                <button class="btn btn-secondary" onclick="showRegister()">注册账号</button>
            </div>
        `;
        commentForm.style.display = 'block';
    }
}

// 编辑文章
function editPost(id) {
    showLoading();
    
    fetch(`${API_BASE}/posts/${id}`)
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.post) {
            hideAllSections();
            document.getElementById('editPostForm').style.display = 'block';
            document.getElementById('editPostId').value = data.post.id;
            document.getElementById('editPostTitle').value = data.post.title;
            document.getElementById('editPostContent').value = data.post.content;
        } else {
            showMessage(data.error || '加载文章失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('加载文章失败: ' + error.message, 'error');
    });
}

// 删除文章
function deletePost(id) {
    if (!confirm('确定要删除这篇文章吗？')) {
        return;
    }
    
    const token = localStorage.getItem('token');
    showLoading();
    
    fetch(`${API_BASE}/posts/${id}`, {
        method: 'DELETE',
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.message) {
            showMessage(data.message, 'success');
            showHome();
        } else {
            showMessage(data.error || '删除文章失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('删除文章失败: ' + error.message, 'error');
    });
}

// 创建评论
function createComment(event) {
    event.preventDefault();
    
    const content = document.getElementById('commentContent').value.trim();
    const postId = document.getElementById('commentPostId').value;
    const token = localStorage.getItem('token');
    
    // 验证评论内容
    if (!content) {
        showMessage('请输入评论内容', 'error');
        return;
    }
    
    if (content.length < 2) {
        showMessage('评论内容至少需要2个字符', 'error');
        return;
    }
    
    if (content.length > 500) {
        showMessage('评论内容不能超过500个字符', 'error');
        return;
    }
    
    // 禁用提交按钮防止重复提交
    const submitBtn = event.target.querySelector('button[type="submit"]');
    const originalText = submitBtn.textContent;
    submitBtn.disabled = true;
    submitBtn.textContent = '发表中...';
    
    showLoading();
    
    fetch(`${API_BASE}/comments`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ content, post_id: parseInt(postId) })
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.message) {
            showMessage(data.message, 'success');
            document.getElementById('commentContent').value = '';
            // 重新加载评论列表
            loadComments(postId);
        } else {
            showMessage(data.error || '发表评论失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('发表评论失败: ' + error.message, 'error');
    })
    .finally(() => {
        // 恢复提交按钮
        submitBtn.disabled = false;
        submitBtn.textContent = originalText;
    });
}

// 加载评论
function loadComments(postId) {
    fetch(`${API_BASE}/comments/post/${postId}`)
    .then(response => response.json())
    .then(data => {
        displayComments(data.comments || []);
        // 更新评论数显示
        updateCommentCount(data.comments ? data.comments.length : 0);
    })
    .catch(error => {
        console.error('加载评论失败:', error);
        document.getElementById('commentsList').innerHTML = '<p style="text-align: center; color: #999;">加载评论失败</p>';
    });
}

// 更新评论数显示
function updateCommentCount(count) {
    const commentSection = document.querySelector('.comments-section h3');
    if (commentSection) {
        commentSection.textContent = `评论 (${count})`;
    }
    
    // 同时更新文章标题下方的评论数
    const commentCountDisplay = document.getElementById('commentCountDisplay');
    if (commentCountDisplay) {
        commentCountDisplay.innerHTML = `<i class="fas fa-comments"></i> ${count}评论`;
    }
}

// 显示评论
function displayComments(comments) {
    const container = document.getElementById('commentsList');
    
    if (!comments || comments.length === 0) {
        container.innerHTML = '<p style="text-align: center; color: #666;">暂无评论，快来发表第一条评论吧！</p>';
        return;
    }
    
    container.innerHTML = comments.map(comment => `
        <div class="comment-item fade-in">
            <div class="comment-meta">
                <span><i class="fas fa-user"></i> ${comment.user.username}</span>
                <span><i class="fas fa-calendar"></i> ${formatDate(comment.created_at)}</span>
                ${currentUser && comment.user_id === currentUser.id ? `
                    <button class="btn btn-small btn-danger" onclick="deleteComment(${comment.id})">删除</button>
                ` : ''}
            </div>
            <div class="comment-content">${comment.content.replace(/\n/g, '<br>')}</div>
        </div>
    `).join('');
}

// 格式化日期显示
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

// 更新字符计数器
function updateCharCount(postId) {
    let textarea, charCount;
    
    if (postId) {
        // 文章列表中的评论表单
        textarea = document.getElementById(`commentContent-${postId}`);
        charCount = document.getElementById(`charCount-${postId}`);
    } else {
        // 文章详情页的评论表单
        textarea = document.getElementById('commentContent');
        charCount = document.getElementById('charCount');
    }
    
    if (textarea && charCount) {
        const count = textarea.value.length;
        charCount.textContent = count;
        
        // 根据字符数改变颜色
        if (count > 450) {
            charCount.style.color = '#dc3545';
        } else if (count > 400) {
            charCount.style.color = '#ffc107';
        } else {
            charCount.style.color = '#666';
        }
    }
}

// 切换评论表单显示
function toggleCommentForm(postId) {
    console.log(`toggleCommentForm called with postId: ${postId}`);
    
    if (!currentUser) {
        showMessage('请先登录后发表评论', 'error');
        setTimeout(() => {
            showLogin();
        }, 1000);
        return;
    }
    
    const commentForm = document.getElementById(`commentForm-${postId}`);
    console.log(`commentForm element:`, commentForm);
    
    if (!commentForm) {
        console.error(`评论表单元素未找到: commentForm-${postId}`);
        return;
    }
    
    if (commentForm.style.display === 'none' || commentForm.style.display === '') {
        commentForm.style.display = 'block';
        // 聚焦到文本框
        setTimeout(() => {
            const textarea = document.getElementById(`commentContent-${postId}`);
            if (textarea) {
                textarea.focus();
            }
        }, 100);
    } else {
        commentForm.style.display = 'none';
        // 清空表单
        const textarea = document.getElementById(`commentContent-${postId}`);
        if (textarea) {
            textarea.value = '';
            updateCharCount(postId);
        }
    }
}

// 切换评论列表显示
function toggleComments(postId) {
    console.log(`toggleComments called with postId: ${postId}`);
    console.log(`currentUser:`, currentUser);
    
    const commentsList = document.getElementById(`commentsList-${postId}`);
    console.log(`commentsList element:`, commentsList);
    console.log(`commentsList display style:`, commentsList.style.display);
    
    if (!commentsList) {
        console.error(`评论列表元素未找到: commentsList-${postId}`);
        return;
    }
    
    // 检查当前显示状态
    const isHidden = commentsList.style.display === 'none' || commentsList.style.display === '';
    console.log(`isHidden: ${isHidden}`);
    
    if (isHidden) {
        console.log(`Showing comments for postId: ${postId}`);
        commentsList.style.display = 'block';
        loadCommentsForPost(postId);
    } else {
        console.log(`Hiding comments for postId: ${postId}`);
        commentsList.style.display = 'none';
    }
}

// 为特定文章加载评论
function loadCommentsForPost(postId) {
    console.log(`loadCommentsForPost called for postId: ${postId}`);
    const commentsList = document.getElementById(`commentsList-${postId}`);
    if (!commentsList) {
        console.error(`评论列表元素未找到: commentsList-${postId}`);
        return;
    }
    
    commentsList.innerHTML = '<div class="loading-comments">加载评论中...</div>';
    console.log(`Making API call to: ${API_BASE}/comments/post/${postId}`);
    
    fetch(`${API_BASE}/comments/post/${postId}`)
    .then(response => {
        console.log(`API response status: ${response.status}`);
        return response.json();
    })
    .then(data => {
        console.log(`API response data:`, data);
        displayCommentsForPost(postId, data.comments || []);
        // 更新评论数显示
        updateCommentCountForPost(postId, data.comments ? data.comments.length : 0);
    })
    .catch(error => {
        console.error('加载评论失败:', error);
        if (commentsList) {
            commentsList.innerHTML = '<p style="text-align: center; color: #999;">加载评论失败</p>';
        }
    });
}

// 显示特定文章的评论
function displayCommentsForPost(postId, comments) {
    console.log(`displayCommentsForPost called for postId: ${postId}, comments:`, comments);
    const container = document.getElementById(`commentsList-${postId}`);
    console.log(`Container found:`, container);
    
    if (!container) {
        console.error(`Container not found: commentsList-${postId}`);
        return;
    }
    
    if (!comments || comments.length === 0) {
        console.log(`No comments found, showing empty message`);
        container.innerHTML = '<p style="text-align: center; color: #666;">暂无评论，快来发表第一条评论吧！</p>';
        return;
    }
    
    console.log(`Rendering ${comments.length} comments`);
    const commentsHTML = comments.map(comment => `
        <div class="comment-item fade-in">
            <div class="comment-meta">
                <span><i class="fas fa-user"></i> ${comment.user.username}</span>
                <span><i class="fas fa-calendar"></i> ${formatDate(comment.created_at)}</span>
                ${currentUser && comment.user_id === currentUser.id ? `
                    <button class="btn btn-small btn-danger" onclick="deleteCommentFromPost(${comment.id}, ${postId})">删除</button>
                ` : ''}
            </div>
            <div class="comment-content">${comment.content.replace(/\n/g, '<br>')}</div>
        </div>
    `).join('');
    
    console.log(`Generated HTML:`, commentsHTML);
    container.innerHTML = commentsHTML;
    console.log(`Container after setting innerHTML:`, container);
}

// 更新特定文章的评论数
function updateCommentCountForPost(postId, count) {
    const commentCountText = document.getElementById(`commentCountText-${postId}`);
    if (commentCountText) {
        commentCountText.textContent = count;
    }
}

// 加载特定文章的评论数
function loadCommentCountForPost(postId) {
    console.log(`Loading comment count for post ${postId}`);
    fetch(`${API_BASE}/comments/post/${postId}`)
    .then(response => response.json())
    .then(data => {
        const count = data.comments ? data.comments.length : 0;
        console.log(`Post ${postId} has ${count} comments`);
        updateCommentCountForPost(postId, count);
    })
    .catch(error => {
        console.error('加载评论数失败:', error);
    });
}

// 提交评论
function submitComment(event, postId) {
    event.preventDefault();
    
    const content = document.getElementById(`commentContent-${postId}`).value.trim();
    if (!content) {
        showMessage('请输入评论内容', 'error');
        return;
    }
    
    const token = localStorage.getItem('token');
    if (!token) {
        showMessage('请先登录', 'error');
        return;
    }
    
    const submitBtn = event.target.querySelector('button[type="submit"]');
    const originalText = submitBtn.textContent;
    submitBtn.disabled = true;
    submitBtn.textContent = '发表中...';
    
    showLoading();
    
    fetch(`${API_BASE}/comments`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ content, post_id: parseInt(postId) })
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.message) {
            showMessage(data.message, 'success');
            // 清空表单
            document.getElementById(`commentContent-${postId}`).value = '';
            updateCharCount(postId);
            // 隐藏评论表单
            toggleCommentForm(postId);
            // 重新加载评论列表
            if (document.getElementById(`commentsList-${postId}`).style.display !== 'none') {
                loadCommentsForPost(postId);
            } else {
                // 如果评论列表未显示，则显示并加载
                document.getElementById(`commentsList-${postId}`).style.display = 'block';
                loadCommentsForPost(postId);
            }
        } else {
            showMessage(data.error || '发表评论失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('发表评论失败: ' + error.message, 'error');
    })
    .finally(() => {
        // 恢复提交按钮
        submitBtn.disabled = false;
        submitBtn.textContent = originalText;
    });
}

// 删除评论
function deleteCommentFromPost(commentId, postId) {
    if (!confirm('确定要删除这条评论吗？')) {
        return;
    }
    
    const token = localStorage.getItem('token');
    showLoading();
    
    fetch(`${API_BASE}/comments/${commentId}`, {
        method: 'DELETE',
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.message) {
            showMessage(data.message, 'success');
            loadCommentsForPost(postId);
        } else {
            showMessage(data.error || '删除评论失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('删除评论失败: ' + error.message, 'error');
    });
}

// 删除评论
function deleteComment(id) {
    if (!confirm('确定要删除这条评论吗？')) {
        return;
    }
    
    const token = localStorage.getItem('token');
    showLoading();
    
    fetch(`${API_BASE}/comments/${id}`, {
        method: 'DELETE',
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.message) {
            showMessage(data.message, 'success');
            loadComments(currentPostId);
        } else {
            showMessage(data.error || '删除评论失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('删除评论失败: ' + error.message, 'error');
    });
}

// 滚动到评论区
function scrollToComments() {
    const commentsSection = document.querySelector('.comments-section');
    if (commentsSection) {
        commentsSection.scrollIntoView({ behavior: 'smooth' });
    }
}

// 滚动到评论表单
function scrollToCommentForm() {
    const commentForm = document.getElementById('commentForm');
    if (commentForm) {
        commentForm.scrollIntoView({ behavior: 'smooth' });
        // 聚焦到文本框
        setTimeout(() => {
            const textarea = document.getElementById('commentContent');
            if (textarea) {
                textarea.focus();
            }
        }, 500);
    }
}
